/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useCallback, useRef, useEffect } from "react";
import { connect } from "dva";
import { useInterval } from "ahooks";
import { Chart, Geom, Axis, Tooltip, Coord, Legend, Guide } from "bizcharts";
import DataSet from "@antv/data-set";
import CommonBorder from "./Wrappers/CommonBorder";
import NoDate from "./Wrappers/NoDate";
import { gradualTextColumn } from "./_utils";

const { DataView } = DataSet;

const YzBrandsRate = ({ dispatch, isParentFull, loading, title = "近7日入库品牌占比", token }) => {
  const [pieData, setPieData] = useState([]);
  const [hasData, setHasData] = useState(false);
  const heightRef = useRef({});
  const [height, setHeight] = useState(0);
  const [firstBrand, setFirstBrand] = useState({ name: "", percent: "" });
  const brandIndex = useRef(1);
  const timer = useRef(null);

  const fetchData = useCallback(
    () => {
      dispatch({
        type: "chartData/getBrandRateRange",
        payload: {
          token,
        },
      }).then((res = []) => {
        const dv = new DataView();
        dv.source(res).transform({
          type: "rename",
          map: {
            ratio: "percent",
          },
        });
        setHasData(res.length > 0);
        const { rows = [] } = dv;
        const { brand, percent } = rows[0] || {};
        setFirstBrand({
          name: brand || "--",
          percent: percent ? `${percent}%` : "0%",
        });
        setPieData(dv);
      });
    },
    [token, dispatch]
  );

  useInterval(() => {
    const { rows = [] } = pieData;
    const { length } = rows;
    if (brandIndex.current >= length) {
      brandIndex.current = 0;
      return;
    }
    const { brand, percent } = rows[brandIndex.current] || {};
    setFirstBrand({
      name: brand || "--",
      percent: percent ? `${percent}%` : "0%",
    });
    brandIndex.current++;
  }, 3000);

  useEffect(
    () => {
      timer.current = setTimeout(() => {
        heightRef.current && setHeight(heightRef.current.clientHeight);
      }, 1000);
      return () => {
        timer.current && clearTimeout(timer.current);
      };
    },
    [isParentFull]
  );

  useEffect(fetchData, [fetchData]);
  useInterval(fetchData, 1000 * 60 * 60);

  return (
    <CommonBorder title={title} loading={loading}>
      <div style={{ height: "100%" }} ref={heightRef}>
        {hasData ? (
          <Chart
            style={{ backgroundColor: "rgba(15, 24, 55, 0.7)" }}
            height={height}
            data={pieData}
            forceFit
            padding={["auto", "auto", "auto", "auto"]}
          >
            <Legend
              clickable={false}
              position="right-center"
              marker="square"
              textStyle={{
                fill: gradualTextColumn,
                fontSize: 20,
              }}
              name="brand"
              itemFormatter={text => {
                const { rows = [] } = pieData;
                let str = "";
                rows.forEach(({ brand, percent } = {}) => {
                  if (brand == text) {
                    str = `${text}${percent}%`;
                  }
                });

                return str;
              }}
            />
            <Coord type="theta" innerRadius={0.65} radius={0.75} />
            <Axis name="percent" />
            <Tooltip
              showTitle={false}
              itemTpl="<li><span style=&quot;background-color:{color};&quot; class=&quot;g2-tooltip-marker&quot;></span>{name}: {value}</li>"
            />
            <Geom
              type="intervalStack"
              position="percent"
              color="brand"
              tooltip={[
                "brand*percent",
                (brand, percent) => {
                  percent = `${percent}%`;
                  return {
                    name: brand,
                    value: percent,
                  };
                },
              ]}
              style={{
                lineWidth: 0,
                stroke: "#fff",
              }}
            />
            <Guide>
              <Guide.Text
                top
                position={["50%", "50%"]}
                content={`${firstBrand.percent}`}
                style={{ textAlign: "center", fontSize: 20, fill: gradualTextColumn }}
                offsetY={-12}
              />
              <Guide.Text
                top
                position={["50%", "50%"]}
                content={`${firstBrand.name}`}
                style={{ textAlign: "center", fontSize: 20, fill: gradualTextColumn }}
                offsetY={12}
              />
            </Guide>
          </Chart>
        ) : (
          <NoDate title="暂无数据" style={{ height }} />
        )}
      </div>
    </CommonBorder>
  );
};

export default connect(({ global, loading }) => ({
  token: global.screenToken,
  loading: loading.effects["chartData/getBrandRateRange"],
}))(YzBrandsRate);
